﻿#include "glad/glad.h"
#include "GLWidget.h"

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

#include <iostream>
using namespace std;

void windowResize(int width, int height)
{
    Width = width;
    Height = height;
    cout << width << "*" << height << endl;
    glViewport(0, 0, width, height);
}

GLWidget *GLWidget::getInstance()
{
    static GLWidget widget;
    return &widget;
}

GLWidget::GLWidget()
{
    glutInitWindowSize(Width, Height);
    // 初始化窗口
    setScreenFull(false);

    if (window < 0) {
        std::cout << "Failed to create GLFW window" << std::endl;
        exit(-1);
    }

    // 初始化 GLAD
    if (!gladLoadGL()) {
        std::cout << "Failed to initialize GLAD" << std::endl;
        exit(-1);
    }

    glutReshapeFunc(windowResize);
    // glfwSetCursorPosCallback(window, mouseMove);
    // glfwSetMouseButtonCallback(window, mousePress);

    // 深度测试
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_MULTISAMPLE);

    glViewport(0, 0, Width, Height);
}

GLWidget::~GLWidget()
{
    glutDestroyWindow(window);
}

void GLWidget::setScreenFull(bool is_full)
{
    window = glutCreateWindow("CreationEngine");
    if (is_full) {
        glutFullScreen();
    } else {
        glutReshapeWindow(Width, Height);
    }
}

unsigned int loadTexture(const char *path)
{
    unsigned int textureID;
    glGenTextures(1, &textureID);

    int width, height, nrComponents;
    unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
    if (data) {
        GLenum format = 3;
        if (nrComponents == 1)
            format = GL_RED;
        else if (nrComponents == 3)
            format = GL_RGB;
        else if (nrComponents == 4)
            format = GL_RGBA;

        glBindTexture(GL_TEXTURE_2D, textureID);
        glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    }

    stbi_image_free(data);
    return textureID;
}